(ns njws-agent.jobs
  (:require [com.stuartsierra.component :as component]
            [org.zalando.stups.friboo.system.cron :refer [def-cron-component job]]
            [org.zalando.stups.friboo.log :as log]
            [org.zalando.stups.friboo.config :refer [require-config]]
            [clojurewerkz.quartzite.scheduler :as qs]
            [clojurewerkz.quartzite.triggers :as t]
            [clojurewerkz.quartzite.jobs :as j]
            [clojurewerkz.quartzite.jobs :refer [defjob]]
            [clojurewerkz.quartzite.schedule.simple :refer [schedule with-repeat-count with-interval-in-milliseconds]]
            [influxdb-clojure.core :as influxdb]
            [njws-agent.sql :as sql]
            [njws-agent.utils :as utils]
            [overtone.at-at :refer [every]]))

(def opts {:retention-policy "autogen"})

(def one-minute-millis
  (* 60 1000))

(def default-configuration
  {:jobs-cpu-count        2
   :jobs-every-ms         (* 2 one-minute-millis)
   :jobs-initial-delay-ms 1000})

(defn get-plc-values
  [max-id db]
  (let [plc-values (sql/get-all-last-values {:id max-id} {:connection db})
        min-id (:id (last plc-values))]
    (try
      (println "plc-id:" max-id)
      (println plc-values)
      (map #(first (conj [] {:measurement (:description %) :time (.getTime (:timestamp %)) :fields {:value (:value %) :src-id (str min-id)}})) plc-values)

      ;; (doseq [point (sql/get-all-last-values {:id plc-id} {:connection db})]
      ;;     (println point)
      ;;    (conj points {:measurement "cpu_load_short"
      ;;                  :fields      {:value (:value point)}}))
      (catch Exception e
        (log/error e "get plc values error")))))

(defn insert-plc-values
  [configuration points]
  ;;(println "insert " points (:influxdb-url configuration) (:influxdb-dbname configuration))
  (if-not (nil? points)
    (do
      (influxdb/write-points (influxdb/connect (:influxdb-url configuration) (:influxdb-name configuration) (:influxdb-pwd configuration)) (:influxdb-dbname configuration) points opts)
      (println (:src-id (:fields (first points))))
      (utils/write-value "./lasttime.txt" (:src-id (:fields (first points)))))
    ))


(def-cron-component
  Jobs [db]

  (let [{:keys [every-ms initial-delay-ms]} configuration]
    (every every-ms #(try (insert-plc-values configuration (get-plc-values (utils/slurp-if-exists "./lasttime.txt") db)) (catch Exception e (log/error e "job error"))) pool
           :initial-delay initial-delay-ms
           :desc "revoke expired access requests")))